package com.qububu.common.user.control;

import static com.qububu.utils.ParamConverter.assertNotEmpty;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qububu.common.user.dto.UserInfoDto;
import com.qububu.common.user.dto.UserInfoDto.Sex;
import com.qububu.common.user.dto.UserLoginInfoDto;
import com.qububu.common.user.dto.UserLoginInfoDto.LoginType;
import com.qububu.common.user.service.UserService;
import com.qububu.systemBase.exceptions.SessionTimeoutException;
import com.qububu.utils.CodeImgGenerater;
import com.qububu.utils.DateUtil;
import com.qububu.utils.MD5Util;
import com.qububu.utils.ParamConverter;
import com.qububu.utils.SystemConstants;
import com.qububu.utils.SystemUtil;
import com.qububu.utils.SystemValidate;

/*
 * 用户登录注册的处理
 * */
@Controller
@RequestMapping("/user")
public class UserControl {
	
	@Resource
	private UserService userService;
	
	
	@RequestMapping("/regist")
	public String returnRegist(){
		
		return "regist";
	}

	@RequestMapping("/goodsInfo")
	public String returngoodsInfo(){
			
		return "goodsInfo";
	}
	
	@RequestMapping("/personInfo")
	public String toPersonInfo(){
		
		return "personInfo";
	}
	
	@RequestMapping("/checkcode")
	@ResponseBody
	public void checkcode(HttpServletRequest request, HttpServletResponse response){

		CodeImgGenerater codeGenerator = new CodeImgGenerater();
		char[] codeChars = codeGenerator.createRandomChars();
		request.getSession().setAttribute("code", String.valueOf(codeChars));
		
		OutputStream outStream = null;
		try {
			outStream = response.getOutputStream();
			ImageIO.write(codeGenerator.creatImageFromChars(codeChars), "JPEG", outStream);
			outStream.flush();
		}
		catch(IOException ex) {
			throw new IllegalStateException(ex);
		}
		finally {
			try {
				if (outStream != null) {
					outStream.close();
				}
			}
			catch(IOException exp) {
				//logger.warn("Fail to close response's outputStream.", exp);
			}
			outStream = null;
		}
	}
	
	/**
	 * @功能 验证验证码是否正确
	 * 
	 * @return boolean true:正确 ,false:错误
	 * */
	@RequestMapping(value="/ajaxuserRegistcheck")
	@ResponseBody
	public boolean userRegistcheck(HttpServletRequest request, HttpServletResponse response) {
		
		boolean flag = false;
		
		if (!SystemValidate.isEmpty(request.getParameter("userRegistyancheck") ) ) {
		
			String userRegistyancheck = request.getParameter("userRegistyancheck");
			
			String str = (String)request.getSession().getAttribute("code");
			
			// 不区分大小写的验证码验证
			if(str.equalsIgnoreCase(userRegistyancheck) )
			{
				flag = true;
			}
		}
		
		return flag	;
	} 

	/**
	 * @功能 用户注册
	 * */
	@RequestMapping("/addregist")
	public String addRegist(HttpServletResponse response, HttpServletRequest request){
	
		String userId = SystemUtil.getUUIDString();
		String registEmail = ParamConverter.assertEmailString(assertNotEmpty(request.getParameter("email")).trim());
		String nickName = SystemUtil.convertSpecialMark(assertNotEmpty(request.getParameter("nickname")).trim());
//		String password = assertNotEmpty(request.getParameter("password"));
		// 还缺一个密码和确认密码的对比验证
		String registSex = assertNotEmpty(request.getParameter("sex"));
		String registBirthday = ParamConverter.assertIsDateString(assertNotEmpty(request.getParameter("birthday")));
		String positionId = assertNotEmpty(request.getParameter("positionId"));
		String clientIp = SystemUtil.getRequestIp(request);
		
		UserLoginInfoDto userLoginInfo = checkAndCreateUserLoginInfoDtoEntity(request);
		UserInfoDto userInfo = createUserInfoDtoEntity(userId, nickName, registBirthday, registSex, registEmail, clientIp, null, positionId, request.getContextPath());
		
		UserInfoDto infoDto = userService.doAddUser(userInfo, userLoginInfo);
		
		if (infoDto != null) {
			request.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_NAME, infoDto);
			request.getSession().setAttribute(SystemConstants.USER_LOGININFO, userLoginInfo);
			
			return "redirect:/user/infocenter";
		} else {
			return "redirect:/user/regist";
		} 
		
	}
	
	/**
	 * @功能 验证该邮箱是否可用
	 * 
	 * @return true:可用, false:不可用
	 * */
	@RequestMapping("/ajaxCheckUserRegistEmailExist")
	@ResponseBody
	public boolean ajaxCheckUserRegistEmailExist(HttpServletRequest request, HttpServletResponse response) {
		
		String userRegistEmail = ParamConverter.assertEmailString(assertNotEmpty(request.getParameter("userRegistEmail")));
		
		return userService.doCheckEmailAlreadyExist(userRegistEmail.trim()) ;
	}
	
	/**
	 * @author ZCW
	 * @throws SessionTimeoutException 数据过期异常
	 * @功能 进入主页的中间跳转页面
	 * */
	@RequestMapping("/infocenter")
	public String infoCenter(HttpServletRequest request, HttpServletResponse response) throws SessionTimeoutException {
		
		UserInfoDto user = (UserInfoDto) request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME);
		
		if (user != null) {
//			System.out.println("\n\n----------------性别是---------------------" + user.getUserSex() +"-----\n\n");
//			System.out.println("\n\n--------" + user.showBirthdayInString() +"--"+user.getNickName()+"--"+String.valueOf(user.getUserId()) +"--"+user.getUserLogoUrl()+"--"+user.showRegisterDateInString()+"--"+user.getUserRegistIp()+"-----\n\n");
			
			return "infocenter";
		} else {
			
			throw new SessionTimeoutException("用户注册完登录时, URL: "+request.getRequestURI());
		}
	}
	
	/**
	 * @功能 ajax验证用户登录信息
	 * 
	 * @return true: 登录成功, false: 登录失败
	 * */
	@RequestMapping("/ajaxLogin")
	@ResponseBody
	public Map<String, Object> ajaxCheckLogin(HttpServletRequest req) {
		
		Map<String, Object> resultMap = null;
		
//		System.out.println("\n\n--------------ajax登录-----------\n\n");
		
		UserLoginInfoDto loginInfo = checkAndCreateUserLoginInfoDtoEntity(req);

		UserInfoDto infoDto =  userService.doCheckUserIsLegal(loginInfo);
		
		resultMap = new HashMap<String, Object>();
		
		if (infoDto != null) {
			
			req.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_NAME, infoDto);
			req.getSession().setAttribute(SystemConstants.USER_LOGININFO, loginInfo);
			
//			System.out.println("\n\n--------------session中保存数据成功mmmmmmmmmmmmm-----------\n\n");
		
			resultMap.put("result", SystemConstants.AJAX_SUCCESS);
			resultMap.put("loginMessage", infoDto);
		} else {
			resultMap.put("result", SystemConstants.AJAX_FAILED_ALERT);
		}
		
		return resultMap;
	}
	
	/**
	 * @功能 进入个人中心
	 * */
	@RequestMapping("/userCenter")
	public String userCenter() {
		
		return "personInfo";
	}
	
	/**
	 * @author HQ
	 * @功能 根据用户id修改用户信息
	 * @param userId传入的用户id
	 */
	@RequestMapping("/userModify")
	@ResponseBody
	public Map<String, Object> userModify(HttpServletRequest request, HttpServletResponse response){
		
		Map<String, Object> userMap = new HashMap<String, Object>();
		
//		UserInfoDto userInfo = (UserInfoDto) request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME);
//		String userId = userInfo.getUserId();
		String userId = "13";/*------临时测试数据------*/
		userId = SystemUtil.encrypt(userId);/*------临时测试数据------*/
		
		String nickName = SystemUtil.convertSpecialMark(assertNotEmpty(request.getParameter("nickName")));
		String userBirthday = ParamConverter.assertIsDateString(assertNotEmpty(request.getParameter("userBirthday")));
		String userEamil = ParamConverter.assertEmailString(assertNotEmpty(request.getParameter("userEamil")));
		String userSex = assertNotEmpty(request.getParameter("userSex"));

		String userLogoUrl = assertNotEmpty(request.getParameter("userLogoUrl"));
		String positionId = assertNotEmpty(request.getParameter("positionId"));
		UserInfoDto userInfoDto = createUserInfoDtoEntity(userId, nickName, userBirthday, userSex, userEamil, null, userLogoUrl, positionId, request.getContextPath());
		UserInfoDto userModify = userService.doModifyUser(userInfoDto);
		
		userMap.put("result", SystemConstants.AJAX_SUCCESS);
		userMap.put("userModify", userModify);
		
		return userMap;
	}
	
	
	/******************私有代码***********************/
	
	/**
	 * @param email 客户端获取的email
	 * @param password 客户端获取的密码
	 * @return 封装好的UserLoginInfoDto类
	 * */
	private UserLoginInfoDto checkAndCreateUserLoginInfoDtoEntity(HttpServletRequest req) {
		
		String email = ParamConverter.assertEmailString(assertNotEmpty(req.getParameter("email")));
		String password = assertNotEmpty(req.getParameter("password") );
		String loginType = "ORDINARY";
		
		UserLoginInfoDto userLoginInfoDto = new UserLoginInfoDto(); 
		
		userLoginInfoDto.setLoginId(email);
		userLoginInfoDto.setPsw(MD5Util.generateForPassword(password));
		userLoginInfoDto.setLoginType(LoginType.getLoginType(loginType));
		
		return userLoginInfoDto;
	}
	
	/**
	 * @param userLogoUrl 用户头像地址, 如果没有则设为null
	 * @param clientIp 用户注册或者修改时的ip 从系统中获得
	 * @return 封装好的UserInfoDto类
	 * */
	private UserInfoDto createUserInfoDtoEntity(String userId, String nickName, String registBirthday, String registSex, String registEmail, String clientIp, String userLogoUrl, String positionId, String contextPath) {
		
		UserInfoDto userInfoDto = new UserInfoDto(userId, positionId);
		
		if (SystemValidate.isEmpty(userLogoUrl) ) {
			
			if (registSex.equals(Sex.FEMALE.toString() ) ) {

				userLogoUrl = contextPath + SystemConstants.DEFAULT_USER_LOGO_URL_WOMAN;
			} else if (registSex.equals(Sex.MALE.toString() ) ) {
				
				userLogoUrl = contextPath + SystemConstants.DEFAULT_USER_LOGO_URL_MAN;
			}
		}
		
		// 获取系统当前时间
		int nowTime = DateUtil.convertCurrentDTTMtoInt();
		
		userInfoDto.setNickName(nickName);
		userInfoDto.setUserBirthday(DateUtil.decodeFromDTString(registBirthday));
		userInfoDto.setUserSex(Sex.getSex(registSex));
		userInfoDto.setUserEamil(registEmail);
		userInfoDto.setUserRegistDttm(nowTime);
		userInfoDto.setUserRegistIp(clientIp);
		userInfoDto.setUserLogoUrl(userLogoUrl);
		
		return userInfoDto;
	}
	
	/*********************************管理员***********************************/
	
	@RequestMapping("admin/adminCenter")
	public String adminInfoCenter() {
		
		return "admin";
	}
	
	@RequestMapping("admin/infoAdminLogin")
	public String adminLogin(HttpServletRequest req) {
		
		return "adminLogin";
	}
	
	@RequestMapping("admin/submitAdminLogin")
	public String submitAdminLogin(HttpServletRequest req) {

		String loginType = assertNotEmpty(req.getParameter("loginType"));
		String email = ParamConverter.assertEmailString(assertNotEmpty(req.getParameter("email")));
		String password = assertNotEmpty(req.getParameter("password"));
		UserLoginInfoDto loginInfo = new UserLoginInfoDto();
		loginInfo.setLoginId(email);
		loginInfo.setPsw(MD5Util.generateForPassword(password));
		loginInfo.setLoginType(LoginType.getLoginType(loginType));
		
		UserInfoDto userInfo =  userService.doCheckUserIsLegal(loginInfo);
		
		if (userInfo != null) {
			req.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_NAME, userInfo);
			req.getSession().setAttribute(SystemConstants.USER_LOGININFO, loginInfo);
			return "redirect:adminCenter";
		} else {
			return "redirect:infoAdminLogin";
		}
	}
	
}